package handlers

import (
	"github.com/gin-gonic/gin"
	"go-caipu/pkg/install/config"
	"go-caipu/pkg/install/database"
	"go-caipu/pkg/install/dto"
	"net/http"
	"os"
	"path/filepath"
)

func CheckDBTest(c *gin.Context) {
	var config dto.Database
	if err := c.ShouldBindJSON(&config); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"success": false,
			"error":   err.Error(),
		})
		return
	}
	if err := database.InitDB(config); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"success": false,
			"error":   err.Error(),
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"message": "db连接成功!",
	})

}
func CheckRedisTest(c *gin.Context) {
	var redis dto.Redis
	if err := c.ShouldBindJSON(&redis); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"success": false,
			"error":   err.Error(),
		})
		return
	}
	if err := database.InitRedisConn(redis); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"success": false,
			"error":   err.Error(),
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"message": "Redis配置已成功",
	})
}

// GetInstallStatus 获取安装状态
func GetInstallStatus(c *gin.Context) {
	// 检查配置文件是否存在
	configPath := filepath.Join(".", "config", "default.yaml")
	_, err := os.Stat(configPath)
	isInstalled := err == nil

	c.JSON(http.StatusOK, gin.H{
		"installed": isInstalled,
	})
}

// ConfigureDatabase 配置数据库和Redis
func ConfigureDatabase(c *gin.Context) {
	var configDto dto.InstallConfig
	if err := c.ShouldBindJSON(&configDto); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"success": false,
			"error":   err.Error(),
		})
		return
	}

	// 验证数据库类型
	if configDto.Database.Type == "" {
		configDto.Database.Type = "mysql" // 默认使用MySQL
	}
	if configDto.Database.Type != "mysql" && configDto.Database.Type != "sqlite" {
		c.JSON(http.StatusBadRequest, gin.H{
			"success": false,
			"error":   "不支持的数据库类型，请选择 mysql 或 sqlite",
		})
		return
	}
	//验证数据库连接
	if err := database.InitDB(configDto.Database); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"success": false,
			"error":   "数据库连接失败：" + err.Error(),
		})
		return
	}
	//验证redis
	if configDto.DeploymentType == "cluster" {
		if err := database.InitRedisConn(configDto.Redis); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{
				"success": false,
				"error":   "redis连接失败：" + err.Error(),
			})
			return
		}
	}
	//创建数据库
	if err := database.CreateDatabase(configDto.Database); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"success": false,
			"error":   "创建数据库失败：" + err.Error(),
		})
		return
	}
	if err := config.UpdateAndWriteConfig(configDto); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"success": false,
			"error":   "配置保存失败：" + err.Error(),
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"message": "配置已保存",
	})

}

// FinishInstall 完成安装
func FinishInstall(c *gin.Context) {

	c.JSON(http.StatusOK, gin.H{
		"success":  true,
		"message":  "安装完成",
		"redirect": "/",
	})
}
